package com.java.common;

import java.io.PrintWriter;
import java.text.DecimalFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class CommonUtil {
	
	/**
	 * 将url加上相对地址后重定向指定URL
	 * @param request
	 * @param response
	 * @param url 相对url，必须以~/�?��
	 */
	public static void redirectURL(HttpServletRequest request,HttpServletResponse response,String url) throws Exception{
		if(url.indexOf("~/")==-1){
			throw new RuntimeException("相对URL写法错误!");
		}
		String toUrl=url;
		String contextPath = request.getContextPath();
		if(!contextPath.equals("")) {
			if(!contextPath.substring(contextPath.length()-1).equals("/")){
				contextPath += "/";
			}
		}else{
			contextPath = "/";
		}
		toUrl = toUrl.replaceAll("~/", contextPath);
		response.sendRedirect(toUrl);
		
	}
	
	
	
	/**
	 * 将数据写入请求响应中
	 * @param response 请求响应
	 * @param mes 消息
	 */
	public static void createResponseJson(HttpServletResponse response, String mes){
		try{
			response.setContentType("application/json;charset=UTF-8");
			PrintWriter pw = response.getWriter();
			pw.write(mes);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 流水号自动增加，左补零
	 * 1->002
	 * @param liuShuiHao
	 * @return
	 */
	public static String haoAddOne(String liuShuiHao,int len){
		String STR_FORMAT = "";
		for(int i=0;i<len;i++) STR_FORMAT+="0";
		
	    Integer intHao = Integer.parseInt(liuShuiHao);
	    intHao++;
	    DecimalFormat df = new DecimalFormat(STR_FORMAT);
	    return df.format(intHao);
	}

}
